package ntu.metaweb.storage;

import java.io.IOException;

import rice.p2p.commonapi.Endpoint;
import rice.p2p.commonapi.Id;
import rice.p2p.commonapi.rawserialization.InputBuffer;
import rice.p2p.commonapi.rawserialization.OutputBuffer;
import ntu.p2p.dht.DHTContentKey;

public class WebPageKey implements DHTContentKey {

	private static final long serialVersionUID = 6154429623548819395L;
	
	private Id id;
	private String url;
	
	public static WebPageKey build (InputBuffer buf, Endpoint endpoint)
			throws IOException {
		return new WebPageKey(buf, endpoint);
	}
	
	public WebPageKey(String url) {
		this.id = rice.pastry.Id.build(url.getBytes());
		this.url = url;
	}
	
	protected WebPageKey(InputBuffer buf, Endpoint endpoint) throws IOException {
		this.id = endpoint.readId(buf, buf.readShort());
		this.url = buf.readUTF();
	}
	
	@Override
	public Id getId() {
		return id;
	}

	@Override
	public void serialize(OutputBuffer buf) throws IOException {
		buf.writeShort(this.id.getType());
		this.id.serialize(buf);
		buf.writeUTF(url);
	}
	
	public int hashCode() {
		return id.hashCode() + url.hashCode();
	}
	
	public boolean equals(Object o) {
		if ((o == null) || !(o instanceof WebPageKey))
			return false;
		WebPageKey key = (WebPageKey) o;
		return this.id.equals(key.id) && this.url.equals(key.url);
	}

	public String toString() {
		return url;
	}
}
